export const splitUrl = (url: string) => {
  try {
    if (!url) return

    // 定义正则表达式
    const regex = /^(?<protocol>[^:]+):\/\/(?<hostname>[^\/]+)(?<path>\/.*)?$/;

    // 使用正则表达式匹配URL
    const match = url.match(regex);

    if (match && match.groups) {
      const { protocol, hostname, path } = match.groups;
      return {
        protocol: protocol,
        hostname: protocol + '://' + hostname,
        path: path || '/'
      };
    } else {
      throw new Error('Invalid URL');
    }
  } catch (error) {
    console.error('Invalid URL:', error, url);
    return null;
  }
}
export function formatSwaggerToRequests1(swaggerData) {
  const isOAS3 = swaggerData.openapi?.startsWith('3') || swaggerData.swagger?.startsWith('3');

  // 获取基础URL组件
  // const baseURLComponents = {
  //   schemes: swaggerData.schemes || ['http'], // 默认HTTP协议
  //   host: swaggerData.host || 'localhost',    // 默认本地主机
  //   basePath: swaggerData.basePath || ''      // 默认无基础路径
  // };
  // 解析基础URL组件（支持OAS3 servers定义）
  const baseURLComponents = getBaseURLComponents(swaggerData, isOAS3);

  return Object.entries(swaggerData.paths).flatMap(([path, pathItem]) => {
    return Object.entries(pathItem).map(([method, endpoint]) => {
      // 生成完整URL（支持多协议）
      const urls = generateFullUrls(path, baseURLComponents);

      // 基础请求信息
      const baseRequest = {
        title: endpoint.summary || path.split('/').pop(),
        method: method.toUpperCase(),
        path: convertPathParams(path),
        urls, // 包含所有可能的完整URL
        parameters: {
          headers: [],
          pathParams: [],
          queryParams: [],
          body: null,
          formData: null,
          urlencoded: null
        }
      };

      // 处理通用参数（保持原有逻辑）
      processCommonParams(endpoint, baseRequest, isOAS3);

      // 处理请求体（保持原有逻辑）
      isOAS3
        ? processOAS3RequestBody(endpoint, baseRequest)
        : processSwagger2RequestBody(endpoint, baseRequest);

      // 添加安全认证参数
      addSecurityParams(endpoint, baseRequest, swaggerData);

      return baseRequest;
    });
  });
}
// 新增：统一获取基础URL组件
function getBaseURLComponents(swaggerData, isOAS3) {
  if (isOAS3) {
    return parseOAS3Servers(swaggerData.servers);
  }
  return {
    schemes: swaggerData.schemes || ['http'],
    host: swaggerData.host || 'localhost',
    basePath: swaggerData.basePath || ''
  };
}

// 新增：解析OAS3服务器配置
function parseOAS3Servers(servers) {
  const defaultComponents = {
    schemes: ['http'],
    host: 'localhost',
    basePath: ''
  };

  if (!servers || servers.length === 0) return defaultComponents;

  try {
    const serverUrl = servers[0].url;
    const parsedUrl = new URL(serverUrl);

    return {
      schemes: [parsedUrl.protocol.replace(/:$/, '')],
      host: parsedUrl.host,
      basePath: parsedUrl.pathname.replace(/\/$/, '') // 移除末尾斜杠
    };
  } catch (e) {
    console.error('解析服务器地址失败:', e);
    return defaultComponents;
  }
}

// 优化后的URL生成方法
function generateFullUrls(path, { schemes, host, basePath }) {
  return schemes.map(scheme => {
    // 标准化路径处理
    const cleanPath = path.startsWith('/') ? path : `/${path}`;
    const fullBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;

    // 使用URL API确保路径正确拼接
    try {
      const baseUrl = new URL(`${scheme}://${host}`);
      const fullUrl = new URL(
        `${fullBasePath}${cleanPath}`.replace(/\/+/g, '/'),
        baseUrl
      );
      return fullUrl.toString().replace(/\{(.*?)\}/g, ':$1');
    } catch (e) {
      // 降级方案：手动拼接
      return `${scheme}://${host}${fullBasePath}${cleanPath}`
        .replace(/([^:])\/+/g, '$1/')
        .replace(/\{(.*?)\}/g, ':$1');
    }
  });
}
// 转换路径参数格式：{id} → :id
function convertPathParams(path) {
  return path.replace(/\{(.*?)\}/g, ':$1');
}

// 处理公共参数（header/path/query）
function processCommonParams(endpoint, request, isOAS3) {
  (endpoint.parameters || []).forEach(param => {
    const paramType = getParamType(param.in);
    if (!paramType) return;

    // 新增示例提取逻辑
    const exampleValue = getSwagger2ExampleValue(param) ||
      getParamExample(param, isOAS3);

    request.parameters[paramType].push({
      name: param.name,
      required: param.required || false,
      example: exampleValue,
      description: param.description || '',
      type: param.type || (isOAS3 && param.schema?.type) || 'string'
    });
  });
}
// 新增：专门处理Swagger 2.0的示例结构
function getSwagger2ExampleValue(param) {
  if (!param.examples) return null;

  // 获取第一个示例键名
  const exampleKeys = Object.keys(param.examples);
  if (exampleKeys.length === 0) return null;

  // 返回第一个示例的值
  return param.examples[exampleKeys[0]]?.value;
}

// 处理OpenAPI 3.0请求体
function processOAS3RequestBody(endpoint, request) {
  if (!endpoint.requestBody) return;

  const content = endpoint.requestBody.content || {};

  // 处理JSON
  if (content['application/json']) {
    request.parameters.body = generateJSONExample(content['application/json'].schema);
  }

  // 处理form-data
  if (content['multipart/form-data']) {
    request.parameters.formData = parseFormContent(
      content['multipart/form-data'].schema,
      'multipart/form-data'
    );
  }

  // 处理x-www-form-urlencoded
  if (content['application/x-www-form-urlencoded']) {
    request.parameters.urlencoded = parseFormContent(
      content['application/x-www-form-urlencoded'].schema,
      'application/x-www-form-urlencoded'
    );
  }
}

// 处理Swagger 2.0请求体
function processSwagger2RequestBody(endpoint, request) {
  const formParams = endpoint.parameters?.filter(p => p.in === 'formData');
  if (formParams?.length) {
    request.parameters.formData = {
      type: endpoint.consumes?.[0] || 'multipart/form-data',
      fields: formParams.map(p => ({
        name: p.name,
        type: p.type === 'file' ? 'file' : 'string',
        required: p.required || false,
        example: getParamExample(p, false)
      }))
    };
    return;
  }

  const bodyParam = endpoint.parameters?.find(p => p.in === 'body');
  if (bodyParam) {
    request.parameters.body = generateJSONExample(bodyParam.schema);
  }
}

// 生成JSON示例
function generateJSONExample(schema) {
  if (!schema) return null;

  const example = schema.example ? clone(schema.example) : {};

  if (schema.properties) {
    Object.entries(schema.properties).forEach(([key, prop]) => {
      if (example[key] === undefined) {
        example[key] = prop.example || generateValueByType(prop);

        // 处理嵌套对象
        if (prop.type === 'object') {
          example[key] = generateJSONExample(prop);
        }

        // 处理数组
        if (prop.type === 'array' && prop.items) {
          example[key] = [generateJSONExample(prop.items)];
        }
      }
    });
  }

  return example;
}

// 解析表单内容
function parseFormContent(schema, contentType) {
  if (!schema?.properties) return null;

  return {
    type: contentType,
    fields: Object.entries(schema.properties).map(([name, prop]) => ({
      name,
      type: prop.format === 'binary' ? 'file' : prop.type || 'string',
      required: schema.required?.includes(name) || false,
      example: prop.example || generateValueByType(prop),
      description: prop.description || ''
    }))
  };
}

// 辅助函数
function getParamType(inValue) {
  const typeMap = {
    header: 'headers',
    path: 'pathParams',
    query: 'queryParams'
  };
  return typeMap[inValue] || null;
}

function getParamExample(param, isOAS3) {
  return param.example ||
    (isOAS3 && param.schema?.example) ||
    param.enum?.[0] ||
    generateValueByType(isOAS3 ? param.schema : param);
}

function generateValueByType(prop) {
  const type = prop?.type || 'string';
  const format = prop?.format;

  const valueMap = {
    string: format === 'date-time' ? new Date().toISOString() :
      prop.enum ? prop.enum[0] : '',
    integer: prop.minimum || 0,
    number: prop.minimum || 0.0,
    boolean: true,
    file: '[File Object]',
    object: {},
    array: []
  };

  return valueMap[type] ?? null;
}

function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

// 添加安全认证参数
function addSecurityParams(endpoint, request, swaggerData) {
  endpoint.security?.forEach(securityReq => {
    Object.entries(securityReq).forEach(([schemeName]) => {
      const scheme = swaggerData.securityDefinitions?.[schemeName];
      if (!scheme) return;

      switch (scheme.type) {
        case 'apiKey':
          addApiKeySecurity(scheme, request);
          break;
        case 'oauth2':
          addOAuth2Security(scheme, request);
          break;
      }
    });
  });
}

function addApiKeySecurity(scheme, request) {
  const param = {
    name: scheme.name,
    required: true,
    type: 'string',
    example: 'special-key', // 示例中的测试密钥
    in: scheme.in,
    description: 'API安全密钥'
  };

  // 根据参数位置添加到对应集合
  const locationMap = {
    header: 'headers',
    query: 'queryParams'
  };

  if (locationMap[scheme.in]) {
    request.parameters[locationMap[scheme.in]].push(param);
  }
}

function addOAuth2Security(scheme, request) {
  request.parameters.headers.push({
    name: 'Authorization',
    required: true,
    type: 'string',
    example: 'Bearer oauth-token',
    description: `OAuth 2.0认证，支持权限：${Object.keys(scheme.scopes).join(', ')}`
  });
}
